package com.kk.miaosha.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kk.miaosha.Vo.AdminQuery;
import com.kk.miaosha.Vo.AdminVo;
import com.kk.miaosha.Vo.RoleVo;
import com.kk.miaosha.entity.*;
import com.kk.miaosha.exception.R;
import com.kk.miaosha.securityEntity.UserDetail;
import com.kk.miaosha.service.*;
import com.kk.miaosha.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : K k
 * @date : 11:27 2020/10/13
 */
@RestController
@RequestMapping("acl")
@Slf4j
@Api(value = "AclController",description = "管理员业务接口")
public class AclController {

    @Autowired
    private RoleService roleService; //角色
    @Autowired
    private MenuService menuService; //权限
    @Autowired
    private UserService userService; //用户
    @Autowired
    private UserRoleService userRoleService; //用户角色关系

    //----------权限管理----------
    //查询权限
    @GetMapping("/menu/getMenuList")
    public R getMenuList(){
        List<Menu> list=menuService.findAllMenu();
        return R.ok().data("children",list);
    }


    @ApiOperation(value = "递归删除菜单")
    @PostMapping("/menu/removeMenu/{id}")
    public R remove(@PathVariable int id) {
        if (id==1){
            return R.error("无权限删除根目录！");
        }
        menuService.removeChildById(id);
        return R.ok();
    }

    @ApiOperation(value = "根据角色获取菜单")
    @GetMapping("/menu/getRoleMenu/{roleId}")
    public R getRoleMenu(@PathVariable int roleId) {
        HashMap<String, Object> map = menuService.findAllMenuByRole(roleId);
        return R.ok().data(map);
    }

    @ApiOperation(value = "为角色分配权限")
    @PostMapping("/menu/toAssignMenu/{roleId}")
    public R assignMenuToRole(@PathVariable("roleId")Integer roleId,@RequestBody int[] menuList){
        menuService.saveRoleMenu(roleId,menuList);
        return R.ok("更新成功!");
    }

    @ApiOperation(value = "新增菜单")
    @PostMapping("/menu/addMenu")
    public R addMenu(@RequestBody Menu menu) {
        menuService.save(menu);
        return R.ok().data("menu",menu);
    }

    @ApiOperation(value = "修改菜单")
    @PostMapping("/menu/updateMenu")
    public R updateMenu(@RequestBody Menu menu) {
        menuService.updateById(menu);
        return R.ok();
    }

    //----------用户管理------------
    //查询列表
    @PostMapping("/admin/getAdminList/{page}/{limit}")
    public R getAdminList(@PathVariable("page")int page,@PathVariable("limit")int limit,@RequestBody AdminQuery adminQuery){
        Page<User> page1=new Page<>(page,limit);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (adminQuery!=null){
            if (adminQuery.getUsername()!=null && !adminQuery.getUsername().isEmpty()){
                userQueryWrapper.like("user_name",adminQuery.getUsername());
            }
            if (adminQuery.getPhone()!=null && !adminQuery.getPhone().isEmpty()){
                userQueryWrapper.like("phone",adminQuery.getPhone());
            }
            if (adminQuery.getEmail()!=null && !adminQuery.getEmail().isEmpty()){
                userQueryWrapper.like("email",adminQuery.getEmail());
            }
        }

        IPage<User> list = userService.page(page1, userQueryWrapper);
        List<AdminVo> admins=userService.getAdminVoList(list.getRecords());
        return R.ok().data("admins",admins).data("total",list.getTotal());
    }

    //查询单个用户
    @GetMapping("/admin/getAdmin/{userId}")
    public R getAdmin(@PathVariable("userId") int userId){
        User user = userService.getById(userId);
        return R.ok().data("user",user);
    }

    //删除用户
    @PostMapping("/admin/removeAdmin/{userId}")
    public R removeAdmin(@PathVariable("userId") int userId){
        if (userId==1){
            return R.error("无权限删除超级管理员！");
        }
        boolean flag = userService.removeById(userId);
        return R.ok("删除成功");
    }

    //更新用户
    @PostMapping("/admin/updateAdmin")
    public R updateAdmin(@RequestBody User user){
        userService.updateAdmin(user);
        return R.ok("更新成功");
    }

    //添加用户
    @PostMapping("/admin/addAdmin")
    public R addAdmin(@RequestBody User user){
        Map<String, Object> map = userService.register(user);
        return R.ok("添加成功");
    }

    //更改用户状态
    @PostMapping("/admin/updateStatus/{id}")
    public R updateStatus(@PathVariable("id")int id){
        User user = userService.getById(id);
        if (user.getIsHidden()==1) {
            user.setIsHidden(0);
        }else {
            user.setIsHidden(1);
        }
        userService.updateById(user);
        return R.ok();
    }

    //为用户分配角色
    @PostMapping("/admin/toAssignRole/{userId}/{roleId}")
    public R assignRoleToAdmin(@PathVariable("userId")Integer userId,@PathVariable("roleId")Integer roleId){

        UserRole userRole = userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id",userId));
        if (userRole==null){
            userRoleService.save(new UserRole().setRoleId(roleId).setUserId(userId));
            return R.ok("更新成功");
        }else{
            //去重
            userRole.setRoleId(roleId);
            boolean flag = userRoleService.updateById(userRole);
            return flag?R.ok("更新成功！"):R.error("更新失败！");
        }
    }


    //----------角色管理---------
    //查询列表 不做分页
    @GetMapping("/role/getRoleList")
    public R getRoleList(){
        List<Role> roleList = roleService.list(null);
        return R.ok().data("roleList",roleList);
    }

    //用户管理查询角色
    @GetMapping("/role/getRoles")
    public R getRoles(){
        List<RoleVo> roles = roleService.getRoles();
        return R.ok().data("roles",roles);
    }

    //查询单个角色
    @GetMapping("/role/getRole/{roleId}")
    public R getRole(@PathVariable("roleId") int roleId){
        Role role = roleService.getById(roleId);
        return R.ok().data("role",role);
    }

    //删除角色
    @PostMapping("/role/removeRole/{roleId}")
    public R removeRole(@PathVariable("roleId") int roleId){
        if (roleId==1){
            return R.error("无权限删除超级管理员！");
        }

        boolean flag = roleService.removeById(roleId);
        //级联删除
        userRoleService.remove(new QueryWrapper<UserRole>().eq("role_id",roleId));
        return R.ok("删除成功");
    }

    //更新角色
    @PostMapping("/role/updateRole")
    public R updateRole(@RequestBody Role role){
        roleService.updateById(role);
        return R.ok("更新成功");
    }

    //添加角色
    @PostMapping("/role/addRole")
    public R addRole(@RequestBody Role role){
        roleService.save(role);
        return R.ok("添加成功");
    }

}
